package org.jeecg.modules.coupon.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.binarywang.wxpay.bean.request.WxPayRefundV3Request;
import com.github.binarywang.wxpay.bean.result.WxPayRefundV3Result;
import com.github.binarywang.wxpay.service.WxPayService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.coupon.entity.Coupon;
import org.jeecg.modules.coupon.entity.CouponOrder;
import org.jeecg.modules.coupon.entity.MyCoupon;
import org.jeecg.modules.coupon.mapper.CouponMapper;
import org.jeecg.modules.coupon.mapper.CouponOrderMapper;
import org.jeecg.modules.coupon.mapper.MyCouponMapper;
import org.jeecg.modules.coupon.service.ICouponOrderService;
import org.jeecg.modules.order.entity.Order;
import org.jeecg.modules.recharge.entity.Balance;
import org.jeecg.modules.recharge.entity.OrderRecharge;
import org.jeecg.modules.recharge.mapper.BalanceMapper;
import org.jeecg.modules.recharge.mapper.OrderRechargeMapper;
import org.jeecg.modules.recharge.service.IBalanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @Description: 优惠券订单
 * @Author: jeecg-boot
 * @Date:   2024-06-28
 * @Version: V1.0
 */
@Service
public class CouponOrderServiceImpl extends ServiceImpl<CouponOrderMapper, CouponOrder> implements ICouponOrderService {

    @Autowired
    private BalanceMapper balanceMapper;
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private CouponOrderMapper couponOrderMapper;
    @Autowired
    private MyCouponMapper myCouponMapper;
    @Autowired
    private OrderRechargeMapper orderRechargeMapper;
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void payOrder(LoginUser sysUser, Balance balance, CouponOrder order, Coupon coupon) {
        Float orderMoney = Float.valueOf(order.getOrderMoney());
        Float money = balance.getBalance().floatValue();
        balance.setBalance(new BigDecimal(money-orderMoney));
        balanceMapper.updateById(balance);
        order.setPayType("1");
        order.setPayTime(new Date());
        order.setOrderStatus("1");
        couponOrderMapper.updateById(order);
        coupon.setCnt(coupon.getCnt()-1);
        couponMapper.updateById(coupon);
        MyCoupon myCoupon = new MyCoupon();
        myCoupon.setCouponName(coupon.getName())
                .setDuration(coupon.getDuration())
                .setDurationLeft(coupon.getDuration().doubleValue())
                .setSysUserId(order.getSysUserId())
                .setCouponType(coupon.getType())
                .setDisAmt(coupon.getDisAmt())
                .setEffectEndDate(coupon.getEffectEndDate())
                .setEffectStartDate(coupon.getEffectStartDate())
                .setOrigAmt(coupon.getOrigAmt())
                .setQuyuId(coupon.getQuyuId())
                .setUseEndTime(coupon.getUseEndTime())
                .setUseStartTime(coupon.getUseStartTime())
                .setUseStatus(0)
                .setMultipleFlag(coupon.getMultipleFlag())
                .setZixishiId(coupon.getZixishiId())
                .setOrderId(order.getId());
        myCoupon.setEndDate(DateUtils.addDays(new Date(),coupon.getDays()));
        myCouponMapper.insert(myCoupon);

        redisUtil.set("mycoupon:end:" + myCoupon.getId(), "",60*60*24*coupon.getDays());
    }

    public void back4WxPay(String orderId) {
        CouponOrder order = couponOrderMapper.selectById(orderId);
        Float money = Float.valueOf(order.getOrderMoney());
        Result<Integer> res = new Result<Integer>();
        WxPayRefundV3Request request = new WxPayRefundV3Request();
        WxPayRefundV3Request.Amount am = new WxPayRefundV3Request.Amount();
        am.setTotal(((Float) (money * 100)).intValue());//原订单金额
        am.setCurrency("CNY");
        am.setRefund(((Float) (money * 100)).intValue());
        //金额信息
        request.setAmount(am);
        //transaction_id:微信支付订单号
        request.setTransactionId(order.getWxOrderId());
        //商户订单号
        request.setOutTradeNo(order.getOrderNum());
        request.setOutRefundNo("couponorder_return_" + order.getOrderNum());
        request.setNotifyUrl(wxPayService.getConfig().getPayScoreNotifyUrl());

        try {
            //调用微信V3退款API
            WxPayRefundV3Result result = wxPayService.refundV3(request);
            String status = result.getStatus();
            order.setBackStatus("0");
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
        this.baseMapper.updateById(order);
    }

    @Override
    public void back4Balance(String orderId) {

        CouponOrder couponOrder = couponOrderMapper.selectById(orderId);
        if(null != couponOrder){
            couponOrder.setBackStatus("1");
            couponOrderMapper.updateById(couponOrder);
            Coupon coupon = couponMapper.selectById(couponOrder.getCouponId());
            if(null != coupon) {
                coupon.setCnt(coupon.getCnt()+1);
                couponMapper.updateById(coupon);
            }

            Balance balance = balanceMapper.selectOne(new LambdaQueryWrapper<Balance>().eq(Balance::getSysUserId,couponOrder.getSysUserId()));
            if(balance==null){
                balance = new Balance();
                balance.setSysUserId(couponOrder.getSysUserId());
                balance.setBalance(new BigDecimal(0));
            }
            balance.setBalance(balance.getBalance().add(new BigDecimal(couponOrder.getOrderMoney())));
            if(StringUtils.isNotBlank(balance.getId())){
                balanceMapper.updateById(balance);
            }else{
                balanceMapper.insert(balance);
            }
            OrderRecharge recharge = new OrderRecharge();
            recharge.setOrderName("卡券退款-" + couponOrder.getOrderNum());
            recharge.setAmountTotal(String.valueOf(couponOrder.getOrderMoney()));
            recharge.setRechargeTotal(String.valueOf(couponOrder.getOrderMoney()));
            recharge.setSysUserId(couponOrder.getSysUserId());
            recharge.setPayStatus("1");
            orderRechargeMapper.insert(recharge);
        }
    }

    @Override
    public void backMoney(String orderId) {
        CouponOrder order = couponOrderMapper.selectById(orderId);
        if(null != order){
            if(StringUtils.equals(order.getPayType(),"0")){
                this.back4WxPay(orderId);
            }else if(StringUtils.equals(order.getPayType(),"1")){
                this.back4Balance(orderId);
            }
//            MyCoupon myCoupon = myCouponMapper.selectOne(new LambdaQueryWrapper<MyCoupon>().eq(MyCoupon::getOrderId,orderId));
//            if(null != myCoupon){
//                redisUtil.del("mycoupon:end:" + myCoupon.getId());
//            }

        }

    }
}
